<!--
 * @Description: 登录表单
 * @Autor: HuiSir<273250950@qq.com>
 * @Date: 2025-06-06 10:37:22
 * @LastEditTime: 2025-06-06 18:05:45
-->
<template>
    <el-form ref="loginForm" :rules="loginFormRules" :model="loginFormData" class="login-form-box">
        <el-form-item prop="username">
            <el-input v-model="loginFormData.username" clearable placeholder="账号" @keyup.enter="onSubmit">
                <template #prefix>
                    <fy-icon name="user" size="14" color="var(--el-text-color-placeholder)" />
                </template>
            </el-input>
        </el-form-item>
        <el-form-item prop="password">
            <el-input type="password" v-model="loginFormData.password" clearable placeholder="密码"
                @keyup.enter="onSubmit">
                <template #prefix>
                    <fy-icon name="key" size="14" color="var(--el-text-color-placeholder)" />
                </template>
            </el-input>
        </el-form-item>
        <el-button type="primary" @click="onSubmit" :loading="loading" class="btn-go">登录</el-button>
        <el-button link @click="forgetPass" class="forget-pass">忘记密码</el-button>
    </el-form>
</template>
<script lang="ts">
export default {
    name: 'LoginForm',
}
</script>
<script lang="ts" setup>
import { Ref, ref, reactive } from 'vue'
import { FormRules } from 'element-plus'
import { useUserStore } from '@/store'

// store
const userStore = useUserStore()

// emit
const emit = defineEmits(['submit'])

const loading = ref(false)

// ref
const loginForm: Ref = ref(null)

// 登录表单数据
const loginFormData: IUserInfo = reactive({
    username: '',
    password: '',
})

// 表单验证
const loginFormRules: FormRules = reactive({
    username: {
        required: true,
        message: '请输入账号',
        trigger: 'blur',
    },
    password: {
        required: true,
        message: '请输入密码',
        trigger: 'blur',
    },
})

// 提交
const onSubmit = () => {
    // 验证
    loginForm.value.validate(async (valid: boolean) => {
        if (valid) {
            // 登录
            await userStore.login(loginFormData)
            emit('submit')
            return true
        }
        return false
    })
}

const forgetPass = () => {
    console.log("忘记密码")
}

// 弹窗关闭完成
const clear = () => {
    // 清除验证提示
    loginForm.value && loginForm.value.resetFields()
    // 清空表单信息
    Object.assign(loginFormData, {
        username: '',
        password: '',
    })
}

// 暴露给父组件
defineExpose({
    clear
})
</script>
<style scoped lang="scss">
.login-form-box {
    .btn-go {
        width: 100%;
    }

    .forget-pass {
        margin: 5px 0 0 0;
        font-size: 90%;
        color: #999;
    }
}
</style>